/*
 * 用于管理签名数据文件，与本地的文件存储相关联
 * 作者：天天
 * 2015年12月3日
 */
var SignList = function(uid, signame) {
	this.uid = uid || "";
	this.signame = signame;
	this.verifymodel = {};
	var url = "http://211.149.201.21/Verify.ashx";//33890
	var APPID = "A6996268375072";
	var APPKEY = "DF2513D5-2329-E8B0-7064-A9D8D701D282";
	var Dirs = ["./", "data/", "template/"];
	var Types = [".sig", ".txt", ".jpg"];
	var Tails = [".sel.json", ".sig.json", ".tpl.json"];
	var Models = ["SignData", "SignData", "SignTemplate"];
	//模型数据
	var kind = 1;
	//0-搜索结果，1-签名结果，2-模板结果
	var filelist = [[], [], []];
	//保存文件,记录本地文件的状态
	var cloudlist = [[], [], []];
	//云端文件
	//0-自由签名文件
	//1-待认证文件
	//2-模板文件
	//对每个文件--{id:记录id,datafile:数据文件名,dataurl:上传服务器的url,imgfile:图片文件,imgurl:服务器的url,kind:状态,del:false,result:}
	//0-基本，1-签名，2-模板
	var bBusy = false;
	//保存数据文件的列表清单
	this.SaveFileList = function(k, callback) {
		var path = "fs://" + uid + Tails[k];
		api.writeFile({
			path : path,
			data : JSON.stringify(filelist[k])
		}, function(ret, err) {
			//console.log(path);
			if ( typeof callback == 'function')
				callback(ret, err);
		});
	}
	//加载本地的文件列表清单
	this.LoadFileList = function(k, callback) {
		var msg = ["", "暂无本地用户签名数据！", "暂无本地模板签名数据！"];
		var file1 = "fs://" + this.uid + Tails[k];
		api.readFile({
			path : file1
		}, function(ret, err) {
			if (ret.status) {
				var obj1 = JSON.parse(ret.data);
				//console.log(ret.data);
				if ( obj1 instanceof Array)
					filelist[k] = obj1;
			} else {
				console.log(msg[k]);
				filelist[k] = [];
			}
			if ( typeof callback == 'function')
				callback(k, filelist[k]);
		});
	}
	//保存数据文件
	this.SaveFile = function(k, dataname, imgdata, txtdata, callback) {
		var idx = filelist[k].length - 1;
		if (idx >= 0 && filelist[k][idx].datafile.indexOf(dataname) >= 0) {
			api.toast({
				msg : "签名数据已保存!"
			}, 2000);			
			if ( typeof callback == 'function')
				callback(k);			
			return;
		}
		if (bBusy)
			return;
		bBusy = true;
		var file1 = "fs://" + Dirs[k] + dataname + Types[1];
		var file2 = "fs://" + Dirs[k] + dataname + Types[2];

		var o = {};
		o.no = filelist[k].length;
		//序数
		o.id = "";
		o.name = dataname.substring(0, dataname.indexOf("_"));
		o.time = (function(s) {
			var pos1 = s.indexOf("_");
			if (pos1 > 0) {
				var t = s.substring(pos1 + 3);
				t = t.substring(0, 4) + "/" + t.substring(4, 6) + "/" + t.substring(6, 8) + " " + t.substring(8, 10) + ":" + t.substring(10, 12) + ":" + t.substring(12, 14);
				return t
			} else
				return "";
		})(dataname);

		o.datafile = dataname + Types[1];
		o.imgfile = dataname + Types[2];
		o.dataurl = "";
		o.imgurl = "";
		o.del = false;
		o.kind = 0;
		o.result = "";

		var self = this;
		api.writeFile({
			path : file1,
			data : txtdata
		}, function(ret, err) {
			if (ret) {
				api.toast({
					msg : dataname
				}, 1000);
				api.writeFile({
					path : file2,
					data : imgdata
				}, function(ret, err) {
					bBusy = false;
					if (ret) {
						filelist[k].push(o);
						self.SaveFileList(k, function(ret, err) {
							if ( typeof callback == 'function')
								callback(k);
						});
					}
				});
			} else {//错误返回
				bBusy = false;
			}
		});
	};
	function fa0(a, b) {
		return a.datafile.localeCompare(b.datafile);
	}

	function fb0(b, a) {
		return a.datafile.localeCompare(b.datafile);
	}

	function fa1(a, b) {
		var pos1 = a.datafile.indexOf('_');
		var pos2 = b.datafile.indexOf('_')
		var sa = a.datafile.substring(pos1 + 3);
		var sb = b.datafile.substring(pos2 + 3);
		return sa.localeCompare(sb);
	}

	function fb1(b, a) {
		var pos1 = a.datafile.indexOf('_');
		var pos2 = b.datafile.indexOf('_')
		var sa = a.datafile.substring(pos1 + 3);
		var sb = b.datafile.substring(pos2 + 3);
		return sa.localeCompare(sb);
	}

	function fa2(a, b) {
		var sa = a.result;
		var sb = b.result;
		console.log(sa + ',' + sb);
		return sa.localeCompare(sb);
	}

	function fb2(b, a) {
		var sa = a.result;
		var sb = b.result;
		console.log(sa + ',' + sb);
		return sa.localeCompare(sb);
	}

	//排序
	this.Sort = function(k, sel, type, callback) {
		console.log(JSON.stringify(filelist[k]));
		if (type == 0) {
			if (sel == 0)
				filelist[k].sort(fa0);
			else if (sel == 1)
				filelist[k].sort(fa1);
			else if (sel == 2)
				filelist[k].sort(fa2);
		} else {
			if (sel == 0)
				filelist[k].sort(fb0);
			else if (sel == 1)
				filelist[k].sort(fb1);
			else if (sel == 2)
				filelist[k].sort(fb2);
		}
		if ( typeof callback == 'function')
			callback(k, filelist[k]);
	}
	//排序
	this.Filter = function(k, param, callback) {
		console.log(JSON.stringify(param));
		//filelist[0].push(filelist[k][0]);
		var type = param.type || "";
		var name = param.name || "";
		filelist[0] = [];
		//		if(type==0)
		//			type="";
		//		else if(type==1)
		//			type=="_T_";
		//		else
		//			type=="_F_";
		for (var i = 0; i < filelist[k].length; i++) {
			if (filelist[k][i].datafile.indexOf(name) >= 0 && filelist[k][i].datafile.indexOf(type) >= 0)
				filelist[0].push(filelist[k][i]);
		};
		if ( typeof callback == 'function')
			callback(0, filelist[0]);
		//console.log(JSON.stringify(filelist[0]));
	}
	//排序
	this.Search = function(k, sel, type, callback) {
		//console.log(JSON.stringify(filelist[k]));
		filelist[0] = [];
		//清空第一个

		if (type == 0) {
			if (sel == 0)
				filelist[k].sort(fa0);
			else if (sel == 1)
				filelist[k].sort(fa1);
			else if (sel == 2)
				filelist[k].sort(fa2);
		} else {
			if (sel == 0)
				filelist[k].sort(fb0);
			else if (sel == 1)
				filelist[k].sort(fb1);
			else if (sel == 2)
				filelist[k].sort(fb2);
		}
		if ( typeof callback == 'function')
			callback(k, filelist[k]);
	}
	var Results = ['.json', '.verify.json', '.model.json'];
	this.GetResult = function(k, callback) {
		var file1 = "fs://" + this.uid + Results[k];
		console.log(file1);
		var result = {};
		api.readFile({
			path : file1
		}, function(ret, err) {
			if (ret.status) {
				result = JSON.parse(ret.data);
			}
			if ( typeof callback == 'function')
				callback(result);
		});
	}
	//用于模板
	this.UseTemplate = function(ids1, callback) {
		for (var i = 0; i < ids1.length; i++)
			filelist[2][ids1[i]].kind = 1;
		var verifymodel = {
			"status" : false,
			"error" : 0,
			"result" : {
				"score" : [],
				"score1" : [],
				"score2" : [],
				"thr" : 0
			}
		};
		this.SaveFileList(2);
		api.writeFile({
			path : 'fs://' + uid + Results[2],
			data : JSON.stringify(verifymodel)
		}, function(ret, err) {

			if ( typeof callback == "function") {
				callback(2, ids1);
			}
		});
	}
	//取消模板
	this.CancelTemplate = function(ids1, callback) {
		for (var i = 0; i < ids1.length; i++)
			filelist[2][ids1[i]].kind = 0;
		var verifymodel = {
			"status" : false,
			"error" : 0,
			"result" : {
				"score" : [],
				"score1" : [],
				"score2" : [],
				"thr" : 0
			}
		};
		this.SaveFileList(2);
		api.writeFile({
			path : 'fs://' + uid + Results[2],
			data : JSON.stringify(verifymodel)
		}, function(ret, err) {
			if ( typeof callback == "function") {
				callback(2, ids1);
			}
		});
	}
	//模板训练
	this.Train = function(kind, ids1, ids2, mode, callback) {
		var self = this;
		var uid = this.uid;
		var data = [];
		for (var i = 0; i < ids1.length; i++)
			data.push(filelist[2][ids1[i]].id);
		self.verifymodel.tpls = data.join(",");
		//this.verifymodel.score=[];
		var sigs = "";
		console.log(this.verifymodel.tpls);
		var url1 = url + "?uid=" + uid + "&tpl=" + self.verifymodel.tpls + "&sig=" + sigs + "&kind=" + mode;
		api.ajax({
			url : url1
		}, function(ret) {
			console.log(JSON.stringify(ret));
			var result = ret.result || {};
			var thr = result.thr || 0;
			var score = result.score || [];
			if (thr >= 52) {
				for (var i = 0; i < filelist[2].length; i++) {
					filelist[2][i].kind = 0;
				}
				for (var i = 0; i < ids1.length; i++)
					filelist[2][ids1[i]].kind = 1;

				self.SaveFileList(2);
				self.verifymodel.score = score;
				self.verifymodel.thr = thr;
				self.verifymodel.status = true;
				//保存结果
				api.writeFile({
					path : 'fs://' + uid + Results[2],
					data : JSON.stringify(self.verifymodel)
				}, function(ret, err) {
				});
			} else {

			}
			if ( typeof callback == "function") {
				callback(kind, ids1, ret.result || {}, thr);
			}
		});
	}
	//模板签名进行训练
	this.Verify = function(kind, ids1, ids2, mode, callback) {
		var self = this;
		var model = {};
		var uid = self.uid;

		if (ids2.length <= 0) {
			if ( typeof callback == "function") {
				callback(1, ids2, [], 0);
			}
			return;
		}

		for (var i = 0; i < ids2.length; i++) {
			var pos = ids2[i];
			if (pos < 0)
				pos = filelist[1].length + pos;			
			ids2[i]=pos;
		}

		api.readFile({
			path : 'fs://' + uid + Results[2],
		}, function(ret, err) {	
			ret=ret||{};					
			self.verifymodel = JSON.parse(ret.data||{});
			var tpls = self.verifymodel.tpls || "";
			if (self.verifymodel.score.length < 3) {
				api.toast({
					msg : '当前使用模板数少于3，请重新选择合适模板！'
				}, 3000);
				return;
			} else {
				self.Upload(1, ids2, function(k, ret) {
					var data = [];
					for (var i = 0; i < ids2.length; i++) {
						var pos = ids2[i];						
						data.push(filelist[1][pos].id);
					}
					var sigs = data.join(",");
					var url1 = url + "?uid=" + uid + "&tpl=" + self.verifymodel.tpls + "&sig=" + sigs + "&kind=" + mode;

					console.log(url1);

					api.ajax({
						url : url1
					}, function(ret) {
						console.log(JSON.stringify(ret));
						api.writeFile({
							path : 'fs://' + uid + Results[1],
							data : JSON.stringify(ret)
						}, function(ret, err) {
							//coding...
						});
						var result = ret.result || {};
						var thr = result.thr || 0;
						var score = result.score || [];
						var score1 = result.score1 || [];
						if (score1.length == ids2.length) {
							for (var i = 0; i < ids2.length; i++) {
								if (score1[i] >= thr)
									filelist[1][ids2[i]].result = "真";
								else
									filelist[1][ids2[i]].result = "假";
							}
							self.SaveFileList(1);
							self.verifymodel.score = score;
							self.verifymodel.thr = thr;
							//保存结果
							api.writeFile({
								path : 'fs://' + uid + Results[2],
								data : JSON.stringify(self.verifymodel)
							}, function(ret, err) {
							});
							console.log(4);
						}
						if ( typeof callback == "function") {
							console.log(5)
							callback(1, ids2, result, thr);
						}
					});
				});
			}
		});
	}
	//删除所有的数据
	this.DelAllItems = function(k, callback) {
		if (k < 0 || k > 2)
			k = 1;
		if(k==undefined)
			k=1;
		var items = filelist[k];
		var count = items.length;

		var i = count - 1;
		var ids = [];
		
		var self=this;

		(function del() {
			var item = items[i];
			if (item) {
				var fs = api.require('fs');
				fs.remove({
					path : 'fs://' + Dirs[k] + item.datafile,
				}, function(ret, err) {
					fs.remove({
						path : 'fs://' + Dirs[k] + item.imgfile,
					}, function(ret, err) {
						var d = filelist[k].pop();
						console.log(i);
//						if ( typeof callback == "function") {
//							callback(k);
//						}
						if (d.id.length > 0)
							ids.push(d.id);
						i--;
						if (i >=0)
							del();
						else {
							//删除服务器端数据
							if (k == 2) {
								var req = [];
								for (var j = 0; j < ids.length; j++) {
									req.push({
										"method" : "DELETE",
										"path" : "/mcm/api/" + Models[k] + "/" + ids[j]
									});
								}
								var client = new Resource(APPID, APPKEY);
								client.batch(req, function(ret, err) {
									//alert("服务器端数据已删除!");
									if ( typeof callback == "function") {
										callback(k);
									}
								});
							}
						}
					});
				});
			} else {
				i--;
				if (i > 0)
					del();
			}
		})();
	}
	//删除数据
	this.DelItem = function(k, ids, callback) {
		var items = filelist[k];
		var count = items.length;
		//删除服务器端数据
		if (k == 2) {
			var req = [];
			for (var j = 0; j < ids.length; j++) {
				req.push({
					"method" : "DELETE",
					"path" : "/mcm/api/" + Models[k] + "/" + items[ids[j]].id
				});
			}
			var client = new Resource(APPID, APPKEY);
			client.batch(req, function(ret, err) {
				alert("服务器端数据已删除!");
				if ( typeof callback == "function") {
					callback(k, ids);
				}
			});
		}

		for (var i = 0; i < ids.length; i++) {
			var fs = api.require('fs');
			var item = items[ids[i]];
			console.log(JSON.stringify(item));
			fs.remove({
				path : 'fs://' + Dirs[k] + item.datafile
			}, function(ret, err) {
				//console.log(JSON.stringify(ret));
				//console.log(JSON.stringify(err));
			});
			fs.remove({
				path : 'fs://' + Dirs[k] + item.imgfile
			}, function(ret, err) {
				//console.log(JSON.stringify(ret));
				//console.log(JSON.stringify(err));
			});
			filelist[k].splice(ids[i], 1);
		}
		//console.log(JSON.stringify(filelist[k]));
		if (k == 1 && ( typeof callback == "function")) {
			callback(k, ids);
		}
	}
	//加载数据
	this.Init = function(callback1, callback2) {
		this.LoadFileList(1, callback1);
		this.LoadFileList(2, callback2);
	};

	//清除数据
	this.Clear = function(callback) {

	};

	//读取数据
	this.GetItem = function(kind, idx) {
	};

	//读取全部数据
	this.GetAllItem = function(kind) {		
		//console.log(JSON.stringify(filelist[kind]));
		return filelist[kind];
	};

	//查找本地文件
	this.FindLocal = function(kind, callback) {

	};

	//查找服务器文件
	//第一步：计算本地保存的文件列表
	//第二步：从服务器端获取数据
	//第三步：与本地数据比较，计算服务器上更新的数据
	//添加更新的数据。
	this.CloudSync = function(k, skip, callback) {
		var client = new Resource(APPID, APPKEY);
		var model = client.Factory(Models[k]);
		//skip = 0;
		var self = this;
		model.query({
			"filter" : {
				"where" : {
					"userid" : uid
				},
				"skip" : skip,
				"limit" : 20
			}
		}, function(ret, err) {
			//console.log(JSON.stringify(ret));
			if (ret && ret.length > 0) {
				console.log(JSON.stringify(ret.length));
				for (var i = 0; i < ret.length; i++) {
					for (var j = 0; j < filelist[k].length; j++)
						if (ret[i].id == filelist[k][j].id) {
							ret.shift();
							break;
						}
				}
				var arr = [];
				var len = filelist[k].length;
				for (var i = 0; i < ret.length; i++)
					(function(i) {
						var o = {};
						o.no = len + i;
						//序数
						o.id = ret[i].id;
						o.name = ret[i].signame;
						o.time = (function(s) {
							var pos1 = s.indexOf("_");
							if (pos1 > 0) {
								var t = s.substring(pos1 + 3);
								t = t.substring(0, 4) + "/" + t.substring(4, 6) + "/" + t.substring(6, 8) + " " + t.substring(8, 10) + ":" + t.substring(10, 12) + ":" + t.substring(12, 14);
								return t
							} else
								return "";
						})(ret[i].dataname);
						o.datafile = ret[i].dataname + Types[1];
						o.imgfile = ret[i].dataname + Types[2];
						o.dataurl = ret[i].datafile.url;
						o.imgurl = ret[i].imgfile.url;
						o.del = false;
						o.kind = ret[i].kind;
						o.result = ret[i].result;
						filelist[k].push(o);
						//arr.push(o);
						self.SaveFileList(k);
						var tmp = [];
						tmp.push(o);
						//下载文件
						api.download({
							url : o.dataurl,
							savePath : 'fs://' + Dirs[2] + o.datafile,
						}, function(ret, err) {
							//coding...
						});
						api.download({
							url : o.imgurl,
							savePath : 'fs://' + Dirs[2] + o.imgfile,
						}, function(ret, err) {
							if ( typeof callback == 'function')
								callback(k, tmp);
						});
					})(i);
			}
		});
	};

	this.Show = function(k, callback) {
		if ( typeof callback == 'function')
			callback(k, filelist[k]);
	}
	//上传数据文件
	this.Upload = function(k, arridx, callback) {
		if (bBusy)
			return;
		bBusy = true;
		var client = new Resource(APPID, APPKEY);
		var model = client.Factory(Models[k]);
		var count = arridx.length;
		var i = 0;

		var newdata = [];
		//记录新到数据
		console.log(JSON.stringify(arridx));

		if (count <= 0) {
			bBusy = false;
			if ( typeof callback == 'function')
				callback(k, []);
			return;
		}
		(function next() {
			var j = arridx[i];
			var len = filelist[k].length - 1;
			if (j < 0 || j > len)
				j = len;
			if(j<0)
			{
				console.log('Error');
				return;
			}				
			var item = filelist[k][j];
			console.log(JSON.stringify(item.datafile));
			var dataname = item.datafile.substring(0, item.datafile.indexOf('.'));
			if (item.id == "") {
				console.log(JSON.stringify(item.imgfile));
				model.save({
					datafile : {
						isFile : true,
						path : "fs://" + Dirs[k] + item.datafile,
						values : {
							filename : item.datafile
						}
					},
					imgfile : {
						isFile : true,
						path : "fs://" + Dirs[k] + item.imgfile,
						values : {
							filename : item.imgfile
						}
					},
					data : '',
					dataname : dataname,
					signame : item.name,
					kind : 0,
					userid : uid
				}, function(ret, err) {
					bBusy = false;
					//console.log(JSON.stringify(ret));
					console.log(JSON.stringify(filelist[k][j]));
					if (ret&&filelist[k][j]) {								
						filelist[k][j].id = ret.id;
						filelist[k][j].dataurl = ret.datafile.url;
						filelist[k][j].imgurl = ret.imgfile.url;
						newdata.push(filelist[k][j]);
						api.writeFile({
							path : "fs://" + uid + Tails[k],
							data : JSON.stringify(filelist[k])
						}, function(ret, err) {
							if (i == count - 1) {
								api.toast({
									msg : "数据上传成功!"
								}, 1000);
							}
						});
					}
					i++;
					if (i < count)
						next();
					else {//回调
						if ( typeof callback == 'function')
							callback(k, newdata);
					}
				});
			} else {
				i++;
				if (i < count)
					next();
				else {//回调
					bBusy = false;
					if ( typeof callback == 'function')
						callback(k, newdata);
				}

			};
		})();
	}
	//普通签名数据用作模板
	//第1步：拷贝文件，并添加文件到模板文件夹下
	//第2步：先上传作为模板文件
	//第3步：更新本地文件
	this.AsTemplate = function(ids, callback) {
		var req = [];
		var k = 1;
		//逐个上传
		var arr = [];
		var count2 = filelist[2].length;
		var oldPath = [];
		var newPath = [];
		for (var j = 0; j < ids.length; j++) {
			var item = filelist[1][ids[j]];
			item.id = "";
			filelist[2].push(item);
			arr.push(count2 + j);
			var oldPath1 = "fs://" + Dirs[1] + item.imgfile;
			var oldPath2 = "fs://" + Dirs[1] + item.datafile;
			var newPath1 = "fs://" + Dirs[2];
			//+item.imgfile;
			var newPath2 = "fs://" + Dirs[2];
			//+item.datafile;
			oldPath.push(oldPath1);
			oldPath.push(oldPath2);
			newPath.push(newPath1);
			newPath.push(newPath2);
		}
		//递归调用
		var i = 0;
		var count = oldPath.length;
		var self = this;
		(function move() {
			var fs = api.require('fs');
			fs.copyTo({
				oldPath : oldPath[i],
				newPath : newPath[i]
			}, function(ret, err) {
				//console.log(JSON.stringify(ret));
				//console.log(JSON.stringify(err));
				i++;
				if (i < count)
					move();
				else {
					self.Upload(2, arr, callback);
				}
			});
		})();

		//批量上传测试不成功
		//		for (var j = 0; j < ids.length; j++) {
		//			var item=filelist[k][ids[j]];
		//			req.push({
		//				"method" : "POST",
		//				"path" : "/mcm/api/" + Models[k],
		//				"values": {
		//					data : '',
		//					dataname : item.datafile,
		//					signame : signame,
		//					kind : 0,
		//					userid : uid
		//				},
		//				"files":{datafile : "fs://" + Dirs[k] + item.datafile,
		//						 imgfile :	"fs://" + Dirs[k] + item.imgfile
		//				}
		//			});
		//		}
		//		var client = new Resource(APPID, APPKEY);
		//		client.batch(req, function(ret, err) {
		//			console.log(JSON.stringify(ret));
		//			console.log(JSON.stringify(err));
		//		});
	}
	//init();
	//初始化
}